using System;
using System.IO;
using System.Xml;

namespace ICSharpCode.TextEditor.Formatting
{
    public class XmlFormattingStrategy : IFormattingStrategy
    {
        private string SimpleFormat(string xml)
        {
            return xml.Replace("><", ">\r\n<");
        }

        private string IndentedFormat(string xml)
        {
            string empty = string.Empty;
            try
            {
                XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(xml));
                xmlTextReader.WhitespaceHandling = WhitespaceHandling.None;
                StringWriter stringWriter = new StringWriter();
                XmlTextWriter xmlTextWriter = CreateXmlTextWriter(stringWriter, convertTabsToSpaces: false, 4);
                xmlTextWriter.WriteNode(xmlTextReader, defattr: false);
                xmlTextWriter.Flush();
                return stringWriter.ToString();
            }
            catch (Exception)
            {
                return xml;
            }
        }

        private XmlTextWriter CreateXmlTextWriter(TextWriter textWriter, bool convertTabsToSpaces, int indentationSize)
        {
            XmlTextWriter xmlTextWriter = new XmlTextWriter(textWriter);
            if (convertTabsToSpaces)
            {
                xmlTextWriter.Indentation = indentationSize;
                xmlTextWriter.IndentChar = ' ';
            }
            else
            {
                xmlTextWriter.Indentation = 1;
                xmlTextWriter.IndentChar = '\t';
            }
            xmlTextWriter.Formatting = System.Xml.Formatting.Indented;
            return xmlTextWriter;
        }

        public string StringFormat(string content)
        {
            try
            {
                content = IndentedFormat(SimpleFormat(IndentedFormat(content)));
            }
            catch (Exception)
            {
            }
            return content;
        }
    }
}
